package com.example.demo.controller;

import com.example.demo.dao.Creation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.demo.dao.Creation.Operation.*;

@Controller
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${upload_path}")
    private String base_path;

    protected Creation[] generateCreationsFormRequest(HttpServletRequest request){
        List<Creation> list = new ArrayList<>();
        request.getParameterMap().forEach((key, value) -> {
            String v = value[0];
            String[] split = v.split(",");
            if(split.length == 2 && !StringUtils.isEmpty(split[1])){
                Creation.Operation operation = Creation.Operation.valueOf(split[0]);
                String _value = split[1];
                if(operation == like)_value = "%" + split[1] + "%";
                if(operation == left_like)_value = "%" + split[1];
                if(operation == right_like)_value = split[1] + "%";
                list.add(new Creation(key, operation, _value));
            }
        });
        return list.toArray(new Creation[0]);
    }

    @PostMapping("/fileInputUpload")
    @ResponseBody
    @CrossOrigin
    public ResponseEntity fileInputUpload(MultipartHttpServletRequest request){
        ModelMap modelMap = new ModelMap();

        List<String> initialPreview = new ArrayList<>();
        List<ModelMap> initialPreviewConfig = new ArrayList<>();
        modelMap.put("initialPreview", initialPreview);
        modelMap.put("initialPreviewConfig", initialPreviewConfig);
        List<String> urls = new ArrayList<>();
        modelMap.put("url", urls);


        List<Map<String, String>> uploads = upload(request);

        uploads.forEach(upload -> {
            String url = upload.get("url");
            initialPreview.add(url);
            ModelMap ipc = new ModelMap();
            ipc.addAttribute("key", url);
            initialPreviewConfig.add(ipc);
            urls.add(url);
        });

        return ResponseEntity.ok(modelMap);
    }

    @PostMapping("/ckeditorUpload")
    @ResponseBody
    @CrossOrigin
    public ResponseEntity ckeditorUpload(MultipartHttpServletRequest request){
        ModelMap modelMap = new ModelMap();

        List<Map<String, String>> uploads = upload(request);

        if(!uploads.isEmpty()){
            modelMap.addAttribute("url", uploads.get(0).get("url"));
            modelMap.addAttribute("fileName", uploads.get(0).get("originalFilename"));
            modelMap.addAttribute("uploaded", 1);
        }else{
            modelMap.addAttribute("uploaded", 0);
            modelMap.addAttribute("error",
                    new ModelMap("message", "upload error"));
        }

        return ResponseEntity.ok(modelMap);
    }


    private List<Map<String, String>> upload(MultipartHttpServletRequest request){
        List<Map<String, String>> list = new ArrayList<>();

        request.getFileMap().forEach((name, file) -> {
            logger.debug("name:{}", name);
            try {
                file.transferTo(new File(base_path, file.getOriginalFilename()));
                String url = String.format("/upload/%s", file.getOriginalFilename());

                Map<String, String> map = new HashMap<>();
                map.put("url", url);
                map.put("originalFilename", file.getOriginalFilename());

                list.add(map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return list;
    }

    @PostMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(){
        ModelMap modelMap = new ModelMap();
        return ResponseEntity.ok(modelMap);
    }
}
